package view.panel;

import tool.DisableEditTableModel;

import javax.swing.*;

import bean.Commodity;
import dao.ShopDAO;

import java.awt.*;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

public class BillPanel extends JPanel {
    private static final long serialVersionUID = 8176838630754666815L;
    private ShopDAO shopDAO;
    private JScrollPane scrollPane;
    private JTable table;
    private DisableEditTableModel tableModel;
    private String[] columnNames;
    private JPanel southPanel;
    private GridLayout layout;
    private JButton removeSelectedCommoditiesFromCartButton;
    private JButton removeAllCommoditiesFromCartButton;
    private JButton refreshCartButton;
    private JButton billButton;
    
    public boolean cartHasCommodity() {
        return tableModel.getRowCount() > 0 ? true : false;
    }

    public BillPanel(Connection conn) throws ClassNotFoundException, SQLException {
        super(new BorderLayout());
        shopDAO = new ShopDAO(conn);
        setName("结账");
        scrollPane = new JScrollPane();
        tableModel = new DisableEditTableModel();
        columnNames = new String[]{ "商品编号", "商品名称", "商品单价", "购买商品数量", "商品总价" };
        tableModel.setColumnIdentifiers(columnNames);
        table = new JTable(tableModel);
        scrollPane.setViewportView(table);
        add(scrollPane, BorderLayout.CENTER);
        southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        layout = new GridLayout(2, 1);
        southPanel.add(new JPanel(layout));
        southPanel.add(new JPanel(layout));
        southPanel.add(new JPanel(layout));
        removeSelectedCommoditiesFromCartButton = new JButton("从购物车移除选中的商品");
        removeSelectedCommoditiesFromCartButton.addActionListener(actionEvent -> {
            int[] indices = table.getSelectedRows();
            for (int rowIndex = indices.length - 1; rowIndex > -1; rowIndex--) {
                int commodityId = (int) tableModel.getValueAt(indices[rowIndex], 0);
                int purchaseQuantity = (int) tableModel.getValueAt(indices[rowIndex], 3);
                try {
                    Commodity commodity = shopDAO.selectByCommodityId(commodityId);
                    int quantity = commodity.getQuantity();
                    quantity += purchaseQuantity;
                    commodity.setQuantity(quantity);
                    shopDAO.update(commodity);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                tableModel.removeRow(indices[rowIndex]);
            }
        });
        southPanel.add(removeSelectedCommoditiesFromCartButton);
        removeAllCommoditiesFromCartButton = new JButton("从购物车移除全部商品");
        removeAllCommoditiesFromCartButton.addActionListener(actionEvent -> {
            for (int rowIndex = tableModel.getRowCount() - 1; rowIndex > -1; rowIndex--) {
                int commodityId = (int) tableModel.getValueAt(rowIndex, 0);
                int purchaseQuantity = (int) tableModel.getValueAt(rowIndex, 3);
                try {
                    Commodity commodity = shopDAO.selectByCommodityId(commodityId);
                    int quantity = commodity.getQuantity();
                    quantity += purchaseQuantity;
                    commodity.setQuantity(quantity);
                    shopDAO.update(commodity);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                tableModel.removeRow(rowIndex);
            }
        });
        southPanel.add(removeAllCommoditiesFromCartButton);
        refreshCartButton = new JButton("刷新购物车");
        refreshCartButton.addActionListener(actionEvent -> {
            ShopDAO dao = new ShopDAO(conn);
            for (int rowIndex = 0; rowIndex < tableModel.getRowCount(); rowIndex++) {
                int commodityId = (int) tableModel.getValueAt(rowIndex, 0);
                try {
                    Commodity commodity = dao.selectByCommodityId(commodityId);
                    String commodityName = commodity.getCommodityName();
                    tableModel.setValueAt(commodityName, rowIndex, 1);
                    /*BigDecimal salePrice = commodity.getSalePrice();
                    tableModel.setValueAt(salePrice, rowIndex, 2);
                    int purchaseQuantity = (int) tableModel.getValueAt(rowIndex, 3);
                    BigDecimal totalPrice = new BigDecimal(purchaseQuantity).multiply(salePrice);
                    tableModel.setValueAt(totalPrice, rowIndex, 4);*/
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            table.clearSelection();
        });
        southPanel.add(refreshCartButton);
        billButton = new JButton("结账");
        billButton.addActionListener(actionEvent -> {
            BigDecimal totalPrice = BigDecimal.ZERO;
            for (int row = 0; row < tableModel.getRowCount(); row++) {
                totalPrice = totalPrice.add((BigDecimal) tableModel.getValueAt(row, 4));
            }
            if (totalPrice.compareTo(BigDecimal.ZERO) > 0) {
                JOptionPane payOptionPane = new JOptionPane("输入付款金额（不能少于" + totalPrice + "元）", JOptionPane.INFORMATION_MESSAGE);
                payOptionPane.setWantsInput(true);
                JDialog payDialog = payOptionPane.createDialog(this, "输入付款金额");
                payDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                payDialog.setVisible(true);
                String paymentAmountText = (String) payOptionPane.getInputValue();
                try {
                    if (Objects.nonNull(paymentAmountText) && paymentAmountText.length() > 0) {
                        BigDecimal paymentAmount = new BigDecimal(paymentAmountText);
                        if (paymentAmount.compareTo(totalPrice) < 0)
                            JOptionPane.showMessageDialog(null, "付款金额不能小于结算金额");
                        else {
                            BigDecimal rest = paymentAmount.subtract(totalPrice);
                            for (int rowIndex = tableModel.getRowCount() - 1; rowIndex > -1; rowIndex--) {
                                tableModel.removeRow(rowIndex);
                            }
                            JOptionPane.showMessageDialog(null, "付款成功。找零金额为：" + rest + "元");
                        }
                    }
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "付款金额不是有效的值");
                }
            } else {
                JOptionPane.showMessageDialog(null, "购物车内没有任何商品");
            }
        });
        southPanel.add(billButton);
        add(southPanel, BorderLayout.SOUTH);
    }
}
